/**
 * File ChatNiSender.java 
 */
package cs.ni;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import cs.remoteapp.Message;


/**
 * Executes sending requests when a ChatNI request becomes.<p>
 * Package  cs.ni
 * Project ChatSystemG1 - INSA 4INFOA1 - 2013/2014
 * @author Julie DUMONS & Juste OUEDRAOGO
 */
public class UdpSender {
	
	/**
	 * socket used by the udp sender
	 */
	private DatagramSocket socket;
	
	/**
	 * Constructor of UdpSender
	 * @param socket used for the udp transmission
	 */
	public UdpSender(DatagramSocket socket){
		this.socket = socket;
	}
	
	/**
	 * sends an object (signal) to remote user 
	 * @param msg message to be sent
	 * @param destAddr destination ip address
	 * @param destPort destination port
	 */
	public void send(Message msg, InetAddress destAddr, int destPort){
		
		try {
			
			/*
			 * create an object output stream from byte array stream
			 */
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			ObjectOutputStream outPut = new ObjectOutputStream(out);
			
			/*
			 * send the signal to the remote user
			 */
			outPut.writeObject(msg);
			DatagramPacket packet = new DatagramPacket(out.toByteArray(), out.toByteArray().length, destAddr, destPort);
			socket.send(packet);
			
			/*
			 * close the streams
			 */
			outPut.close();
			out.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	
}
